"""
趋势跟踪策略 - 策略示例

策略逻辑:
1. 当价格上涨超过阈值时买入
2. 当价格下跌超过阈值时卖出
3. 基于精确的 strategy_id 控制
"""
import logging
import asyncio
from core.base_strategy import BaseStrategy
from typing import Dict, Any

logger = logging.getLogger("TrendStrategy")

class TrendStrategy(BaseStrategy):
    """趋势跟踪策略"""
    
    async def on_init(self):
        """策略初始化"""
        # 获取参数，设置默认值
        self.symbol = self.params.get("symbol", "SH600000")
        self.threshold = float(self.params.get("threshold", 0.01))  # 1% 阈值
        self.position_size = int(self.params.get("position_size", 100))  # 每次交易100股
        
        # 订阅行情
        await self.subscribe(self.symbol)
        
        # 初始化持仓
        self.last_price = None
        logger.info(f"🎯 趋势策略初始化完成: {self.symbol}, 阈值: {self.threshold:.2%}")
    
    async def on_tick(self, data: Dict[str, Any]):
        """处理行情数据"""
        current_price = data.get("last_price")
        if current_price is None:
            return
        
        logger.debug(f"📊 {self.symbol} 当前价格: {current_price:.2f}, 上次价格: {self.last_price}")
        
        # 第一次收到数据
        if self.last_price is None:
            self.last_price = current_price
            return
        
        # 计算价格变化率
        price_change = (current_price - self.last_price) / self.last_price
        
        # 买入信号: 价格上涨超过阈值
        if price_change > self.threshold and self.positions.get(self.symbol, 0) == 0:
            await self.buy(self.symbol, self.position_size)
            logger.info(f"📈 买入信号: {self.symbol} 价格上涨 {price_change:.2%} > {self.threshold:.2%}")
        
        # 卖出信号: 价格下跌超过阈值
        elif price_change < -self.threshold and self.positions.get(self.symbol, 0) > 0:
            current_position = self.positions.get(self.symbol, 0)
            await self.sell(self.symbol, current_position)
            logger.info(f"📉 卖出信号: {self.symbol} 价格下跌 {abs(price_change):.2%} > {self.threshold:.2%}")
        
        # 更新最后价格
        self.last_price = current_price
    
    async def on_stop(self):
        """策略停止回调"""
        logger.info(f"⏹️ 趋势策略停止: {self.strategy_id}")
        # 【可选】保存策略状态